import React, {useRef, useState, useEffect} from "react";
import {
    ActionType,
    ModalForm,
    ProForm, ProFormDatePicker,
    ProFormDateTimePicker, ProFormDependency, ProFormDigit, ProFormInstance, ProFormMoney, ProFormRadio,
    ProFormSelect,
    ProFormText,
} from "@ant-design/pro-components";
import {BillingExportData, BillingExportPdfData, BillingOverview} from "@/pages/order/billing/list/data";

import moment from 'moment';
import 'moment/locale/zh-cn';


type ExportBillingNoticeProps = {
    modalVisible: boolean;
    onClose: () => void;
    onSuccess: () => void;
    initData: BillingExportData;
};

const formItemLayout = {
    labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
    },
    wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 },
    },
};

const ExportBillingNoticeModalForm: React.FC<ExportBillingNoticeProps> = (props) => {
    const {modalVisible, onClose, onSuccess, initData} = props;
    const [exportModalVisible, handleExportModalVisible] = useState<boolean>(modalVisible);
    /** 分布更新窗口的弹窗 */
    const actionRef = useRef<ActionType>();
    const modalFormRef = useRef<ProFormInstance>();
    const [taxCostValue, setTaxCostValue] = useState<string>('')
    const [totalCostValue, setTotalCostValue] = useState<string>('')
    useEffect(() => {
        handleExportModalVisible(modalVisible);
    }, [modalVisible]);

    useEffect(() => {
        if (!exportModalVisible) {
            onClose();
        }
    }, [exportModalVisible]);

    // 获取当前日期
    const currentDate = new Date();
    // 添加7天
    const expireTime = moment(currentDate.getTime() + (7 * 24 * 60 * 60 * 1000)).format('YYYY-MM-DD HH:mm')

    const handlePdfExport = async (fields: BillingExportPdfData) => {
        const serviceCost = modalFormRef?.current?.getFieldValue("serviceCost");
        const billingStartTime = modalFormRef?.current?.getFieldValue("billingStartTime");
        const billingEndTime = modalFormRef?.current?.getFieldValue("billingEndTime");
        const organizationAddress = modalFormRef?.current?.getFieldValue("organizationAddress");
        const organizationName = modalFormRef?.current?.getFieldValue("organizationName");
        const taxCostPercent = modalFormRef?.current?.getFieldValue("taxCostPercent");
        const billingExpireTime = modalFormRef?.current?.getFieldValue("billingExpireTime");

        const billingExportPdfData: BillingExportPdfData = {
            serviceCost: serviceCost,
            billingStartTime: moment(billingStartTime).format('YYYY-MM-DD HH:mm'),
            billingEndTime: moment(billingEndTime).format('YYYY-MM-DD HH:mm'),
            organizationName: organizationName,
            organizationAddress: organizationAddress,
            totalCost: totalCostValue,
            taxCostPercent: taxCostPercent,
            taxCost: taxCostValue,
            billingExpireTime: moment(billingExpireTime).format('YYYY-MM-DD HH:mm'),
        };


        const base64Param = Buffer.from(JSON.stringify(billingExportPdfData)).toString('base64')
        window.open(API_SERVER.default+'/api/billing/export/pdf?data='+encodeURIComponent(base64Param), '_blank');
        return true;
    };

    return (
        <ModalForm
            title="导出账单通知"
            width="650px"
            open={exportModalVisible}
            onOpenChange={handleExportModalVisible}
            formRef={modalFormRef}
            onFinish={async (values) => {
                const success = await handlePdfExport(values as BillingExportPdfData);
                if (success) {
                    onClose()
                    onSuccess()
                    handleExportModalVisible(false);
                    if (actionRef.current) {
                        actionRef.current.reload();
                    }
                }
            }}
            modalProps={{destroyOnClose: true}}
            initialValues={{
                organizationName: initData.organizationName,
                organizationAddress: initData.organizationAddress,
                serviceCost: initData.serviceCost,
                billingStartTime: initData.billingStartTime,
                billingEndTime: initData.billingEndTime,
            }}
            layout="horizontal"
            {...formItemLayout}
        >
            <ProFormText
                name="organizationName"
                label="公司名称"
                disabled={true}
                hidden={false}
            />
            <ProFormText
                name="organizationAddress"
                label="公司地址"
                disabled={true}
                hidden={false}
            />

            <ProForm.Item
                label="账期"
                style={{height:"32px"}}
            >
                <ProForm.Item
                    rules={[{required: true}]}
                    style={{display: 'inline-block', width: 'calc(40% - 8px)'}}
                >
                    <ProFormDatePicker
                        name="billingStartTime"
                        disabled={true}
                        hidden={false}
                        dataFormat={"YYYY-MM-DD"}
                        initialValue={initData.billingStartTime}
                    />
                </ProForm.Item>
                <span style={{display: 'inline-block', width: '24px', lineHeight: '32px', textAlign: 'center'}} > - </span>
                <ProForm.Item
                    rules={[{required: true}]}
                    style={{display: 'inline-block', width: 'calc(40% - 8px)', margin: '0 8px'}}
                >
                    <ProFormDatePicker
                        name="billingEndTime"
                        disabled={true}
                        hidden={false}
                        initialValue={initData.billingEndTime}
                    />
                </ProForm.Item>
            </ProForm.Item>

            <ProFormDatePicker
                label="付款到期日"
                name="billingExpireTime"
                hidden={false}
                initialValue={expireTime}
            />

            <ProFormMoney
                label="服务费用"
                name="serviceCost"
                rules={[
                    {
                        required: true,
                        message: '请输入单价',
                    },
                ]}
                width={200}
                fieldProps={{addonAfter: "元",precision: 2}}
                placeholder="请输入服务费用"
            />
            <ProFormDigit
                label="增值税率"
                name="taxCostPercent"
                rules={[
                    {
                        required: true,
                        message: '请输入增值税率',
                    },
                ]}
                width={200}
                fieldProps={{addonAfter: "%"}}
                placeholder="请输入服务费用"
                initialValue={6}
            />

            <ProFormDependency name={['serviceCost', 'taxCostPercent']}>
                {({ serviceCost, taxCostPercent }) => {
                    const taxCostValue:number = Number(serviceCost) * (Number(taxCostPercent) / 100.00);
                    const taxCostValueString = taxCostValue.toFixed(2)
                    setTaxCostValue(taxCostValueString)
                    // console.log('ttt serviceCost:'+Number(serviceCost))
                    // console.log('ttt taxCost:'+taxCostValueString)
                    return (
                            <ProFormMoney
                                label="增值税"
                                name="taxCost"
                                width={200}
                                fieldProps={{
                                    addonAfter: "元",
                                    value: Number(taxCostValueString),
                                    precision: 2,
                                }}
                                disabled={true}
                            />
                        );
                    }
                }
            </ProFormDependency>

            <ProFormDependency name={['serviceCost', 'taxCostPercent']}>
                {({ serviceCost, taxCostPercent }) => {
                    const taxCostValue:number = Number(serviceCost) * (Number(taxCostPercent) / 100.00);
                    const taxCostValueString = taxCostValue.toFixed(2)

                    const totalCostValue = Number(serviceCost) + Number(taxCostValueString)
                    const totalCostValueString = totalCostValue.toFixed(2)
                    setTotalCostValue(totalCostValueString)

                    // console.log('serviceCost:'+Number(serviceCost))
                    // console.log('taxCost:'+taxCostValueString)
                    // console.log('totalCostValue:'+totalCostValueString)
                    return (
                        <ProFormMoney
                            label="账单合计"
                            name="totalCost"
                            width={200}
                            fieldProps={{
                                addonAfter: "元",
                                value: Number(totalCostValueString),
                                precision: 2,
                            }}
                            disabled={true}
                        />
                    );
                }
                }
            </ProFormDependency>
        </ModalForm>
    );
}

export default ExportBillingNoticeModalForm;
